﻿using System;
using System.Globalization;
using System.Web.Mvc;
using MyPet.Common;
using MyPet.Models;

using NetDimension.DianDian;
using NetDimension.Json;


namespace MyPet.Controllers
{
    public class DianController : Controller
    {
        public ActionResult Test(string tag, int limit, int offset)
        {
            var oauth = new OAuth("**", "**", "");
            oauth.GetAccessTokenByPassword("**", "**");
            var sinaNew = new Client(oauth);
            string sinceId = MyConfig.GetValue("UpdatePostID");
            limit = int.Parse(MyConfig.GetValue("UpdateCount")) + 1;
            string result = sinaNew.API.Entity.Dian.Tags(sinaNew.OAuth.AccessToken, limit, tag, offset, sinceId, true, true, "html");
            dynamic newValue = JsonConvert.DeserializeObject<object>(result);
            dynamic testResult = newValue["response"]["posts"];
            int i = 1;
            while (true)
            {
                if (i >= testResult.Count)
                {
                    break;
                }
                if (testResult[i]["type"].ToString() == "photo")
                {
                    var doc = new PetPhoto();
                    var postIdStr = (string)testResult[i]["postId"].ToString();
                    doc.postId = postIdStr;
                    doc.type = "photo";
                    dynamic empty = testResult[i]["caption"] == (dynamic)null ? string.Empty : testResult[i]["caption"].ToString();
                    var captionStr = (string)empty;
                    doc.caption = captionStr.StripHtml().Replace("<p>", "").Replace("</p>", "").Replace("<em>", "").Replace("</em>", "");
                    doc.photo = (string) testResult[i]["photos"][0]["altSizes"]["default"]["url"].ToString();
                    doc.photo = doc.photo.Replace("libdd", "srcdd");
                    doc.photos = (string)testResult[i]["photos"][0].ToString();
                    var tagStr = (string)testResult[i]["tags"].ToString();
                    doc.tags = tagStr.Replace("[", "").Replace("]", "");
                    doc.likeCount = int.Parse(testResult[i]["likeCount"].ToString());
                    doc.createTime = (string)testResult[i]["createTime"].ToString();
                    doc.blogUuid = (string)testResult[i]["blogUuid"].ToString();
                    doc.postUrl = (string)testResult[i]["postUrl"].ToString();
                    MongoDBHelper.MongoDBHelper.InsertOne(tag, doc);
                    if (i + 1 == testResult.Count)
                    {
                        MyConfig.SetValue("UpdateTime", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                        MyConfig.SetValue("UpdatePostID", postIdStr);
                    }
                }
                i++;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}